
#include "pomodorotimer.h"
#include "ui_pomodorotimer.h"
#include <QMessageBox>
#include <QDateTime>
#include <QTextStream>

PomodoroTimer::PomodoroTimer(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::PomodoroTimer),
    isRunning(false),
    isPaused(false)
{
    ui->setupUi(this);
    this->setFixedSize(300, 397);

    appIcon = QIcon(":/icons/clock_green.png");
    setWindowIcon(appIcon);

    timer = new QTimer(this);
    connect(timer, &QTimer::timeout, this, &PomodoroTimer::updateTimer);

    ui->taskSummaryEdit->setPlaceholderText("请输入专注总结");
    ui->taskNameEdit->setPlaceholderText("请输入专注名称");
    ui->durationSpinBox->setValue(25);
    ui->pauseButton->setEnabled(false);
    ui->submitButton->setEnabled(false);
}

PomodoroTimer::~PomodoroTimer()
{
    delete ui;
}

void PomodoroTimer::on_startStopButton_clicked()
{
    if (!isRunning) {
        // Start the timer
        int minutes = ui->durationSpinBox->value();
        remainingTime = QTime(0, minutes, 0);
        startTime = QTime::currentTime();

        ui->taskNameEdit->setEnabled(false);
        ui->durationSpinBox->setEnabled(false);
        ui->startStopButton->setText("停止");
        ui->pauseButton->setEnabled(true);

        isRunning = true;
        isPaused = false;
        timer->start(1000);
        updateTimer();
    } else {
        // Stop the timer
        timer->stop();
        stopTime = QTime::currentTime();
        isRunning = false;
        ui->startStopButton->setEnabled(false);
        ui->pauseButton->setEnabled(false);
        ui->submitButton->setEnabled(true);

        QApplication::alert(this); /**< 实现任务栏提示 - 先闪烁，后常亮（约10s闪烁） */

        // Change tray icon color (placeholder)
        this->setStyleSheet("background-color: #FFCCCC;");
    }
}

void PomodoroTimer::on_pauseButton_clicked()
{
    if (isPaused) {
        timer->start(1000);
        ui->pauseButton->setText("暂停");
        isPaused = false;
    } else {
        timer->stop();
        ui->pauseButton->setText("继续");
        isPaused = true;
    }
}

void PomodoroTimer::updateTimer()
{
    remainingTime = remainingTime.addSecs(-1);
    ui->timeLabel->setText(remainingTime.toString("mm:ss"));

    if (remainingTime == QTime(0, 0, 0)) {
        on_startStopButton_clicked();
    }
}

QString PomodoroTimer::formatTimeDiff(const QTime &start, const QTime &end)
{
    int diffMs = start.msecsTo(end); // 获取毫秒差
    if (diffMs < 0) {
        diffMs += 86400000; // 处理跨午夜情况(24小时毫秒数)
    }

    int hours = diffMs / 3600000;      // 计算小时
    int minutes = (diffMs % 3600000) / 60000;  // 计算分钟
    int seconds = (diffMs % 60000) / 1000;     // 计算秒

    return QString("%1:%2:%3")
            .arg(hours, 2, 10, QLatin1Char('0'))
            .arg(minutes, 2, 10, QLatin1Char('0'))
            .arg(seconds, 2, 10, QLatin1Char('0'));
}

void PomodoroTimer::on_submitButton_clicked()
{
    saveTaskLog();
    resetUI();
}

void PomodoroTimer::saveTaskLog()
{
    QDir dir;
    if (!dir.exists("TaskLog")) {
        dir.mkdir("TaskLog");
    }

    QString filename = QDateTime::currentDateTime().toString("yyyy-MM-dd") + ".txt";
    QFile file("TaskLog/" + filename);

    if (file.open(QIODevice::Append | QIODevice::Text)) {
        QTextStream out(&file);
        out << tr("任务名称: ") << ui->taskNameEdit->text() << "\n"; /**< 不用tr包裹显示乱码 */
        out << tr("间长: ") << formatTimeDiff(startTime, stopTime) << "\n";
        out << tr("开始时间: ") << startTime.toString("hh:mm:ss") << "\n";
        out << tr("结束时间: ") << stopTime.toString("hh:mm:ss") << "\n";
        out << tr("提交时间: ") << QTime::currentTime().toString("hh:mm:ss") << "\n";
        out << tr("任务总结: ") << ui->taskSummaryEdit->toPlainText() << "\n";
        out << "----------------------------\n";
        file.close();
    }
}

void PomodoroTimer::resetUI()
{
    ui->taskNameEdit->setEnabled(true);
    ui->taskNameEdit->clear();
    ui->taskNameEdit->setPlaceholderText("请输入专注名称");

    ui->durationSpinBox->setEnabled(true);
    ui->durationSpinBox->setValue(25);

    ui->timeLabel->clear();
    ui->startStopButton->setText("开始");
    ui->startStopButton->setEnabled(true);
    ui->pauseButton->setEnabled(false);
    ui->pauseButton->setText("暂停");

    ui->taskSummaryEdit->clear();
    ui->taskSummaryEdit->setPlaceholderText("请输入专注总结");
    ui->submitButton->setEnabled(false);

    this->setStyleSheet("");
    isRunning = false;
    isPaused = false;
}
